function res = applyrois(s,rois)
%res = applyrois(s,rois) applies the given 'rois' to the scans 's'

%INPUT:  s    = scan or scan structure to be integrated/extracted
%        rois = the ROIs to be applied (from e.g. click2rois2.m)
%OUTPUT: res  = structure with the results:
%               - 'data' is the integrated detector pixels (one column per scan)
%               - 'datan' normalized data
%               - 'datae' poisson error
%               - 'dataen' normalized error
%               - 'monitor' monitor signal from the SPEC file
%               - 'energy' is the common energy scale for all of them (all data are interpolated to this)
%               - 'sum' sum over all scans 
%               - 'sume' error of all scans
%               - 'sumw' error weighted sum
%               - 'sumwe' error of 'sumn'

%integrate over rois
for h=1:length(rois)
    for k=1:length(s)
        for l=1:size(s(1).A,1)
            res(h).data(l,k) = sumy(s(k).A(l,rois(h).indices));                             %data
            res(h).datan(l,k) = sumy(s(k).A(l,rois(h).indices))./s(k).monitor(l);           %normalized data
            res(h).datae(l,k) = sqrt(sumy(s(k).A(l,rois(h).indices)));                      %error
            res(h).dataen(l,k) = sqrt(sumy(s(k).A(l,rois(h).indices)))./s(k).monitor(l);    %normalized error
            res(h).monitor(l,k) = s(k).monitor(l);
        end
    end
end

%bring evergthing onto a common energy grid
energy = s(1).energy_cc;
for h=1:length(rois)
    for k=1:length(s)
        res(h).data(:,k) = interp1(s(k).energy_cc,res(h).data(:,k),energy);
        res(h).datan(:,k) = interp1(s(k).energy_cc,res(h).datan(:,k),energy);
        res(h).datae(:,k) = interp1(s(k).energy_cc,res(h).datae(:,k),energy);
        res(h).dataen(:,k) = interp1(s(k).energy_cc,res(h).dataen(:,k),energy);
        res(h).energy = energy;
        res(h).monitor(:,k) = interp1(s(k).energy_cc,s(k).monitor,energy);
    end    
end
        
%if there is more than one scan, sum over all scans
if length(s)>1
    for n=1:length(rois)
        res(n).sum   = sum(res(n).data,2);
        res(n).sume  = sqrt(sum(res(n).datae.^2,2));
        %
        res(n).datae(res(n).datae==0) = 1;
        res(h).dataen(res(n).dataen==0) = 1;
        %
        res(n).sumw  = (sum(res(n).datan'./res(n).dataen'.^2)./(sum(1./res(n).dataen'.^2)))';
        res(n).sumwe = sqrt(1./sum(1./res(n).dataen'.^2))';
    end
end

